package pl.edu.agh.mobsys.persistence;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import java.util.LinkedList;
import java.util.List;

import pl.edu.agh.mobsys.data.Message;

public class MessageDataHelper {

	private static final String DATABASE_NAME = "xmpp_client.db";
	private static final int DATABASE_VERSION = 1;
	private final String TABLE_NAME;

	private Context context;
	private SQLiteDatabase db;

	private SQLiteStatement insertStmt;
	private final String INSERT;

	public MessageDataHelper(Context context, String tableName) {
		this.context = context;
		this.TABLE_NAME = tableName;
		//this.INSERT = "insert into " + TABLE_NAME + "(name) values (?)";
		this.INSERT = "insert into " + TABLE_NAME + "(content, author, time) values (?, ?, ?)";
		
		OpenHelper openHelper = new OpenHelper(this.context, this.TABLE_NAME);
		this.db = openHelper.getWritableDatabase();
		this.insertStmt = this.db.compileStatement(INSERT);
	}

	public long insert(String content, String author, String time) {
		this.insertStmt.clearBindings();
		this.insertStmt.bindString(1, content);
		this.insertStmt.bindString(2, author);
		this.insertStmt.bindString(3, time);
		return this.insertStmt.executeInsert();
	}

	public void deleteAllMessages() {
		db.execSQL("DELETE FROM " + TABLE_NAME);
	}

	public List<Message> selectAll() {
		List<Message> messagesList = new LinkedList<Message>();
		Cursor cursor = this.db.query(TABLE_NAME, new String[] { "content",
				"author", "time" }, null, null, null, null, "id asc");

		if (cursor.moveToFirst()) {
			do {
				messagesList.add(new Message(cursor.getString(0), cursor
						.getString(1), cursor.getString(2)));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return messagesList;
	}

	private static class OpenHelper extends SQLiteOpenHelper {

		private final String TABLE_NAME;

		OpenHelper(Context context, String tableName) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
			this.TABLE_NAME = tableName;
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE "
					+ this.TABLE_NAME
					+ "(id INTEGER PRIMARY KEY, content TEXT, author TEXT, time TEXT)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w("Example",
					"Upgrading database, this will drop tables and recreate.");
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
	}
}
